import tkinter as tk
from tkinter import filedialog, messagebox
import os
import asyncio
import edge_tts
from datetime import datetime

DEFAULT_VOICE = {
    'Yunyang-云扬': 'zh-CN-YunyangNeural',
    'Xiaoxiao-晓晓': 'zh-CN-XiaoxiaoNeural',
    'Xiaoyi-晓伊': 'zh-CN-XiaoyiNeural',
    'Yunjian-云健': 'zh-CN-YunjianNeural',
    'Yunxi-云希': 'zh-CN-YunxiNeural',
    'Yunxia-云夏': 'zh-CN-YunxiaNeural',
    'liaoning-Xiaobei-晓北辽宁': 'zh-CN-liaoning-XiaobeiNeural',
    'shaanxi-Xiaoni-陕西晓妮': 'zh-CN-shaanxi-XiaoniNeural'
}

async def tts_work(file_path, text, voice="zh-CN-YunyangNeural", rate="+0%", volume="+100%"):
    try:
        tts = edge_tts.Communicate(text=text, voice=voice, rate=rate, volume=volume)
        await tts.save(file_path)
        return True
    except Exception as e:
        messagebox.showerror("错误", f"转换过程中出现错误: {str(e)}")
        return False

def get_voice(file_path, text, voice_name=None):
    voice = voice_name if voice_name else "zh-CN-YunjianNeural"
    return asyncio.run(tts_work(file_path, text, voice))

def create_gui():
    def select_file(entry):
        file_path = filedialog.askopenfilename(filetypes=[("Text files", "*.txt")])
        entry.delete(0, tk.END)
        entry.insert(0, file_path)

    def select_directory(entry):
        directory = filedialog.askdirectory()
        entry.delete(0, tk.END)
        entry.insert(0, directory)

    def run_tts_script():
        voice_choice = voice_var.get()
        voice_id = DEFAULT_VOICE[voice_choice]
        text_path = text_file_entry.get()
        output_dir = output_dir_entry.get()

        if not os.path.exists(text_path):
            messagebox.showerror("错误", "文本文件不存在！")
            return

        text = read_text_file(text_path)
        if text is None:
            return

        if not os.path.exists(output_dir):
            os.makedirs(output_dir)

        timestamp = datetime.now().strftime("%Y%m%d_%H%M%S")
        output_file = os.path.join(output_dir, f"output_{timestamp}.mp3")
        success = get_voice(output_file, text, voice_id)

        if success:
            messagebox.showinfo("完成", "转换完成！")
        else:
            messagebox.showerror("错误", "转换失败！")

    def read_text_file(file_path):
        try:
            with open(file_path, 'r', encoding='utf-8') as f:
                return f.read().strip()
        except Exception as e:
            messagebox.showerror("错误", f"读取文件出错: {str(e)}")
            return None

    root = tk.Tk()
    root.title("文字转语音工具")

    tk.Label(root, text="选择语音：").grid(row=0, column=0, padx=10, pady=5)
    voice_var = tk.StringVar(value='Yunyang-云扬')
    voice_menu = tk.OptionMenu(root, voice_var, *DEFAULT_VOICE.keys())
    voice_menu.grid(row=0, column=1, padx=10, pady=5)

    tk.Label(root, text="选择文本文件：").grid(row=1, column=0, padx=10, pady=5)
    text_file_entry = tk.Entry(root, width=40)
    text_file_entry.grid(row=1, column=1, padx=10, pady=5)
    tk.Button(root, text="浏览", command=lambda: select_file(text_file_entry)).grid(row=1, column=2, padx=10, pady=5)

    tk.Label(root, text="输出目录：").grid(row=2, column=0, padx=10, pady=5)
    
    desktop_path = os.path.join(os.path.expanduser("~"), "Desktop")
    output_dir_entry = tk.Entry(root, width=40)
    output_dir_entry.insert(0, desktop_path)
    output_dir_entry.grid(row=2, column=1, padx=10, pady=5)
    tk.Button(root, text="浏览", command=lambda: select_directory(output_dir_entry)).grid(row=2, column=2, padx=10, pady=5)

    tk.Button(root, text="开始转换", command=run_tts_script).grid(row=3, column=1, pady=20)

    root.mainloop()

if __name__ == "__main__":
    create_gui() 